'''
Created on Oct 15, 2010

@author: oabalbin
'''
import sys
from collections import defaultdict,deque
from RNAseq.arraytools.subset_genes import list_of_names

def nested_dict_factory(): 
    return defaultdict()
  
def nested_dict_factory2(): 
    return defaultdict(nested_dict_factory)


def read_sampleDB(inputfile_name):
    inputfile = open(inputfile_name)
    header = inputfile.next().strip('\n').split(',')
    sample_dict=defaultdict(nested_dict_factory)
    
    # Library name= col2, Flowcell=col3
    lbn, fcn= 2,3
    for i, line in enumerate(inputfile):
        fields=line.strip('\n').split(',')
                
        spname, flowcell = fields[lbn],fields[fcn]  
        #print sample_name, flowcell
        fieldsvals = sum([[fields[0]],[fields[1]],fields[4:]],[])
        sample_dict[spname][flowcell]=sum([[fields[0]],[fields[1]],fields[4:]],[])
        
    inputfile.close()
    return sample_dict
    
        
def get_flowcell_path_sample(sample_dict,samples):
    
    #line, dir_data
    l,cdir=2,7
    sample_paths=defaultdict(nested_dict_factory)
    for sp,fclist in samples.iteritems():
        for fc in fclist: 
            try:
                fcn = fc.split('_') 
                lane, fcn = fcn[1],fcn[2]
                fcinfo = sample_dict[sp][fcn]
                print fcinfo
                path =  fcinfo[cdir]+'/'
                sample_paths[sp][fcn+'_'+lane]=path
    
            except KeyError:
                print "not found", fc, sp
                continue
            
    return sample_paths            

def read_sampleDB_flowcell(inputfile_name):
    inputfile = open(inputfile_name)
    header = inputfile.next().strip('\n').split(',')
    sample_dict=defaultdict(nested_dict_factory)
    
    # Library name= col2, Flowcell=col3
    lbn, fcn,ln= 2,3,4
    for i, line in enumerate(inputfile):
        fields=line.strip('\n').split(',')   
        spname, flowcell, lane = fields[lbn],fields[fcn],fields[ln]
        sample_dict[flowcell][lane]=sum([[spname],[fields[0]],[fields[1]],fields[4:]],[])
        
    inputfile.close()
    return sample_dict


def get_flowcell_path_flowcell(sample_dict,flowcell):
    
    #line, dir_data
    l,cdir=2,8
    sample_paths=defaultdict(nested_dict_factory)
    for sp,fclist in flowcell.iteritems():
        for fc in fclist:
            try:
                fcn = fc.split('_') 
                fcn, lane = fcn[1],fcn[2]
                fcinfo = sample_dict[fcn][lane]
                path =  fcinfo[cdir]+'/'
                sample_paths[sp][fcn+'_'+lane] = path
    
            except KeyError:
                print "not found", fc, sp
                continue
    
    return sample_paths

def get_flow_cell_dict(sample_info):
    sample_names = sample_info.next().strip('\n').split('\t')[1:]
    samples_fc=defaultdict()
    # Custom to get the flow cells, but it need to be changed to manipulate the sample names from oncoseq directly
    for line in sample_info:
        fields = line.strip('\n').split('\t')
        if fields[0] == 'library_ids':
            fc = fields[1:]
            for i,sp in enumerate(sample_names):
                samples_fc[sp] = fc[i].split(',')

    return samples_fc

    
def write_data_paths(dirpaths, outfile_name):
    
    outfile = open(outfile_name,'w')
    for sp in dirpaths:
        for fc, path in dirpaths[sp].iteritems():
            #print sp, fc, path 
            line = [sp,fc,path]
            outfile.write(",".join(line).replace(',','\t')+'\n')
    
    outfile.close()


'''
sample_info = open('/exds/users/oabalbin/projects/how_tos/example_samples_pools.txt')             
samples_file = '/exds/users/oabalbin/projects/alignment_test/pair_prostate_samples'
inputfile_name = '/exds/users/oabalbin/projects/sampleDB_database_10_16_10.csv'
outfile_name = '/exds/users/oabalbin/projects/alignment_test/sample_dirpaths.txt'

# custom because some Oncoseq samples are name inconsistent with sampleDB
samples_fc = get_flow_cell_dict(sample_info)
###
flowcell_dict=read_sampleDB_flowcell(inputfile_name)
dirpaths = get_flowcell_path_flowcell(flowcell_dict, samples_fc)
write_data_paths(dirpaths, outfile_name)
'''






